﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using TY.UC.Common;
using TY.UC.Common.Extension;

namespace TY.UC.Http
{
    /// <summary>
    /// 调用外部接口方法拓展
    /// </summary>
    public partial class HttpHelper
    { /// <summary>
      /// 参数请求(支持https请求)
      /// </summary>
      /// <param name="jsonparam">json字符串</param>
      /// <param name="url">请求地址</param>
      /// <param name="cookies">cookies集合</param>
      /// <param name="sign">是否需要签名验证</param>
      /// <returns>请求结果字符串</returns>
        public static string JsonStrPostRequestHuobi(string jsonparam, string url)
        {
            HttpWebRequest myRequest;
            //http、https请求区分
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                myRequest = WebRequest.Create(url) as HttpWebRequest;
                if (myRequest != null)
                {
                    myRequest.ProtocolVersion = HttpVersion.Version10; 
                }
            }
            else
            {
                myRequest = WebRequest.Create(url) as HttpWebRequest;
            }
            if (myRequest == null) return "";
            //设置头信息
            //myRequest.Accept = "zh-cn";
            myRequest.Method = "POST";
            myRequest.ContentType = "application/json";
            myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36";
            if (true)
            {

                //string timeStamp = GetTimeStamp();
                //string nonce = GetRandom();
                //myRequest.Headers.Add("timestamp", timeStamp); //发起请求时的时间戳（单位：毫秒）
                //myRequest.Headers.Add("nonce", nonce); //发起请求时的时间戳（单位：毫秒）
                ////拼接签名数据,将字符串中字符按升序排序
                //var sortStr = string.Concat((timeStamp + nonce + AppToken + jsonparam).OrderBy(c => c));
                //myRequest.Headers.Add("Signature", Signature); //当前请求内容的数字签名
            }
            if (!string.IsNullOrEmpty(jsonparam))
            {
                var buf = Encoding.UTF8.GetBytes(jsonparam);//转成网络流
                myRequest.ContentLength = buf.Length;
                try
                {
                    //发送表求
                    using (Stream newStream = myRequest.GetRequestStream())
                    {
                        newStream.Write(buf, 0, buf.Length);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            //if (cookies != null)
            //{
            //    myRequest.CookieContainer = new CookieContainer();
            //    myRequest.CookieContainer.Add(cookies);
            //}
            string res = "";
            try
            {
                //获得接口返回值
                HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    res = reader.ReadToEnd();
                    myRequest.Abort();
                    myResponse.Close();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("Http请求异常:" + new { url, jsonparam }, ex);
                throw ex;
            }
            return res;
        }
        #region GetRequest  Get请求
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="param">form表单字典集合</param>
        /// <param name="url">请求地址</param>
        /// <param name="cookies">cookies集合</param>
        /// <returns>请求结果字符串</returns>
        public static string GetStrRequestHuoBiNoProxy(string url, Dictionary<string, string> param, CookieCollection cookies = null)
        {
            if (param != null)
            {
                url += "?";
                foreach (var item in param)
                {
                    url += string.Format("{0}={1}&", item.Key, item.Value);
                }
                url = url.Trim('&');
            }

            HttpWebRequest myRequest;
            //http、https请求区分
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                myRequest = WebRequest.Create(url) as HttpWebRequest;
                if (myRequest != null) myRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myRequest = WebRequest.Create(url) as HttpWebRequest;
            }
            //myRequest.Proxy = new WebProxy("127.0.0.1", 1080);

            //设置头信息
            if (myRequest == null) return "";
            myRequest.Method = "GET";
            myRequest.ContentLength = 0;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36";

            if (cookies != null)
            {
                myRequest.CookieContainer = new CookieContainer();
                myRequest.CookieContainer.Add(cookies);
            }
            //获得接口返回值 
            string res = "";
            int count = 20;
            for (int i = 1; i <= count; i++)
            {
                try
                {
                    HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        res = reader.ReadToEnd();
                        myRequest.Abort();
                        myResponse.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("http/https访问异常：" + new { url }, ex);
                    Thread.Sleep(3000);//等待3秒
                    LogHelper.WriteLog("http/https访问异常，等待3秒，继续访问：" + new { url, param });
                }
            }
            return res;
        }
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="param">form表单字典集合</param>
        /// <param name="url">请求地址</param>
        /// <param name="cookies">cookies集合</param>
        /// <returns>请求结果字符串</returns>
        public static string GetStrRequestHuoBi(string url, Dictionary<string, string> param,CookieCollection cookies = null)
        {
            if (param != null)
            {
                url += "?";
                foreach (var item in param)
                {
                    url += string.Format("{0}={1}&", item.Key, item.Value);
                }
                url = url.Trim('&');
            }

            HttpWebRequest myRequest;
            //http、https请求区分
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                myRequest = WebRequest.Create(url) as HttpWebRequest;
                if (myRequest != null) myRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myRequest = WebRequest.Create(url) as HttpWebRequest;
            }
            if ("is_proxy".GetStrValue().ToLower()!="no")
            {
                myRequest.Proxy = new WebProxy("127.0.0.1", 1080);
            } 
            //设置头信息
            if (myRequest == null) return "";
            myRequest.Method = "GET";
            myRequest.ContentLength = 0;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36";

            if (cookies != null)
            {
                myRequest.CookieContainer = new CookieContainer();
                myRequest.CookieContainer.Add(cookies);
            }
            //获得接口返回值 
            string res="";
            int count = 20;
            for (int i=1;i<= count; i++)
            {
                try
                {
                    HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        res = reader.ReadToEnd();
                        myRequest.Abort();
                        myResponse.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("http/https访问异常：" + new { url },ex); 
                    Thread.Sleep(3000);//等待3秒
                    LogHelper.WriteLog("http/https访问异常，等待3秒，继续访问：" + new { url, param });
                }
            } 
            return res;
        }
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="param">form表单字典集合</param>
        /// <param name="url">请求地址</param>
        /// <param name="cookies">cookies集合</param>
        /// <returns>请求结果字符串</returns>
        public static string GetStrRequest(string url, Dictionary<string, string> param, CookieCollection cookies = null)
        {
            if (param != null)
            {
                url += "?";
                foreach (var item in param)
                {
                    url += string.Format("{0}={1}&", item.Key, item.Value);
                }
                url = url.Trim('&');
            }
           
            HttpWebRequest myRequest;
            //http、https请求区分
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                myRequest = WebRequest.Create(url) as HttpWebRequest;
                if (myRequest != null) myRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myRequest = WebRequest.Create(url) as HttpWebRequest;
            }

            //设置头信息
            if (myRequest == null) return "";
            myRequest.Method = "GET";
            myRequest.ContentLength = 0;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.UserAgent = DefaultUserAgent;
   
            if (cookies != null)
            {
                myRequest.CookieContainer = new CookieContainer();
                myRequest.CookieContainer.Add(cookies);
            }
            //获得接口返回值
            HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
            string res; 
            using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
            {
                res = reader.ReadToEnd();
                myRequest.Abort();
                myResponse.Close();
            }
            return res;
        }

        public static T GetRequest<T>(string url, Dictionary<string, string> param, CookieCollection cookies = null)
        {
            string res = GetStrRequest(url, param, cookies);
            return res.JsonDe<T>();
        }

        #endregion
    }
}
